package com.example.train.common.config.security.filter;

import cn.hutool.crypto.CryptoException;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.train.common.config.security.IgnoreUrlsConfig;
import com.example.train.common.config.security.handler.JwtAuthFailureHandler;
import com.example.train.common.config.security.model.AuthUserDetail;
import com.example.train.common.config.security.utils.JwtTokenUtil;
import com.example.train.common.constant.ErrorConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT登录授权过滤器
 */
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    private IgnoreUrlsConfig ignoreUrlsConfig;

    private AuthenticationFailureHandler failureHandler = new JwtAuthFailureHandler();

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        String authHeader = request.getHeader(this.tokenHeader);
        if (authHeader != null && authHeader.startsWith(this.tokenHead)) {
            String authToken = authHeader.substring(this.tokenHead.length());// The part after "Bearer "

            String failMsg = null;
            String attemptUsername = null;

            try {
                DecodedJWT decode = jwtTokenUtil.decode(authToken);
                attemptUsername = jwtTokenUtil.getUserFromToken(decode);
                log.debug("attempt to verify username:{}", attemptUsername);
                if (attemptUsername != null && SecurityContextHolder.getContext().getAuthentication() == null) {

                    AuthUserDetail userDetails = (AuthUserDetail) userDetailsService.loadUserByUsername(attemptUsername);

                    //检验token
                    DecodedJWT decodedJWT = jwtTokenUtil.verifyJwtToken(userDetails.getTokenSalt(), authToken);

                    if (jwtTokenUtil.isTokenExpired(decodedJWT)) {
                        throw new TokenExpiredException(attemptUsername+" token has expired: " + decodedJWT.getExpiresAt());
                    }

                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }

            } catch (JWTDecodeException e) {
                log.error("JWT decode error: {}, invalid token: {}", e.getMessage(), authToken);
                failMsg = ErrorConstant.JWT_DECODE_ERROR;
            } catch (CryptoException e) {
                log.error("username decrypt error: {}, username encrypt string: {}", e.getMessage(), attemptUsername);
                failMsg = ErrorConstant.USERNAME_DECRYPT_ERROR;
            } catch (TokenExpiredException e) {
                log.error("token has expired: {}",e.getMessage());
                failMsg = ErrorConstant.TOKEN_HAS_EXPIRED;
            } catch (SignatureVerificationException e) {
                log.error("token is invalid: {}", e.getMessage());
                failMsg = ErrorConstant.TOKEN_IS_INVALID;
            }

            if (failMsg != null) {
                unsuccessfulAuthentication(request, response, new AuthenticationServiceException(failMsg));
                return;
            }
        }
        chain.doFilter(request, response);
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        boolean ignore = ignoreUrlsConfig.isIgnoreForRequest(request);

        return ignore;
    }

    protected void unsuccessfulAuthentication(HttpServletRequest request,
                                              HttpServletResponse response, AuthenticationException failed)
            throws IOException, ServletException {
        SecurityContextHolder.clearContext();
        failureHandler.onAuthenticationFailure(request, response, failed);
    }
}
